<?php

namespace App\Repositories;

use App\Models\Category;
use App\Models\Supplier;

class CategoryRepository
{

    public function getList($filter = [], $pageNum = 2, $pageSize = 10): array
    {
        $res = Category::query()
            ->when(!empty($filter['keywords']), function ($query) use ($filter) {
                return $query->where("title", "like", "%{$filter['keywords']}%");
            })
            ->orderBy("id", "desc")
            ->paginate($pageSize, ["*"], null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);

        foreach ($res['items'] as $k => &$v) {
            if (!empty($v['shop_id'])) {
                $v['shop_title'] = Supplier::query()->where("id", $v['shop_id'])->value("title");
            }
        }

        return $res;
    }

    public function getOne($id = null)
    {
        return Category::query()->where("id", $id)->first();
    }

    /**
     * 会员使用
     * @param int $id
     */
    public function getById(int $id = 0)
    {
        return Category::query()->where(["id" => $id, 'status' => 1])->first(['id', 'title']);
    }

    public function saveOrUpdate($data = [], $id = 0)
    {
        if (!empty($data['id']))
            unset($data['id']);

        if (intval($id)) {
            Category::where("id", $id)->update($data);
            return $id;
        } else {
            /* $res = Category::create($data);
             return $res['id'] ?? "";*/
            return Category::create($data)->id;
        }
    }

    /**
     * 删除
     * @param null $id
     */
    public function del($id = null)
    {
        if (!intval($id))
            return retFail("参数错误");

        Category::where(['id' => intval($id)])->delete();

        return retSuc([], "删除成功");
    }

    public function getOptions()
    {
        return Category::query()->where(['status' => 1])
            ->orderBy('sort', "asc")
            ->orderBy("id", "desc")
            ->get(['id', "title"])
            ->toArray();
    }


    /**
     * 批量删除
     * @param null $ids
     */
    public function batchDelete($ids = null)
    {
        if (intval($ids)) {
            Category::where(['id' => $ids])->delete();
        } else {
            Category::whereIn("id", $ids)->delete();
        }
        return retSuc([], "删除成功");
    }

}
